package com.ramos.kuaixiao.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.ramos.kuaixiao.entity.EmpBrand;
import com.ramos.kuaixiao.entity.ShopNew;
import com.ramos.kuaixiao.entity.ShopTypeBean;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.Test;

import java.util.ArrayList;
import java.util.List;

public class EmpBrandDB {
    private static String TAG = "EmpBrandDB";
    private static String TABLE_NAME = "EmpBrand";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
        CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "did" + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
                + "dealer_id" + " CHAR(30)," + "employer_id" + " CHAR(30)," + "brand_id_list" + " CHAR(30),"+ "modifyTime" + " Long);";
        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    public int addAllEmpBrand(List<EmpBrand> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM EmpBrand");
        String sql = "insert into EmpBrand(dealer_id,employer_id,brand_id_list, modifyTime) values(?,?,?,?)";
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        SQLiteStatement stmt = db.compileStatement(sql);
        for (int i = 0; i < customer.size(); i++) {
            stmt.bindString(1, customer.get(i).getDealerId() + "");
            stmt.bindString(2, customer.get(i).getEmpId() + "");
            stmt.bindString(3, customer.get(i).getBrandList() + "");
            stmt.bindString(4, customer.get(i).getModifyTime() + "");
            stmt.execute();
            stmt.clearBindings();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public int updateAllEmpBrand(List<EmpBrand> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        Log.d(TAG, "updateAllEmpBrand:"+customer.size());
        for (int i = 0; i < customer.size(); i++) {
            EmpBrand firstWarehouse = customer.get(i);
            if(hasEmpBrand(firstWarehouse.getEmpId()+"")){
                ContentValues cv = new ContentValues();
                cv.put("brand_id_list", firstWarehouse.getBrandList() + "");
                cv.put("modifyTime", firstWarehouse.getModifyTime() + "");
                db.update("EmpBrand",cv,"employer_id=?", new String[]{firstWarehouse.getEmpId() + ""}) ; //如果有记录，则更新，并返回1，否则返回0*//*
            } else{
                ContentValues cv = new ContentValues();
                cv.put("dealer_id", firstWarehouse.getDealerId()+ "");
                cv.put("employer_id", firstWarehouse.getEmpId() + "");
                cv.put("brand_id_list", firstWarehouse.getBrandList() + "");
                cv.put("modifyTime", firstWarehouse.getModifyTime() + "");
                db.insert("EmpBrand",null, cv) ; //如果有记录，则更新，并返回1，否则返回0
            }
            // 生成的sql是 INSERT INTRO OR REPLACE INTO 这样的 (如果存在就替换存在的字段值. 存在的判断标准是主键冲突, 这里的主键是userId). 下面会介绍这个地方的方法
            //db.insertWithOnConflict("StoreNum",null, cv, SQLiteDatabase.CONFLICT_REPLACE) ; //如果有记录，则更新，并返回1，否则返回0
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        //updateBrand();
        return 0;
    }

    private void updateBrand() {
        String brandList= "";
        List<ShopNew> tmpList = new ArrayList<>();
        List<ShopNew> list = new BrandDB().findAllBrand();

        List<EmpBrand> list1 = new EmpBrandDB().findAllCustomer();

        if(list1.size() > 0 && list.size() > 0){
            for(EmpBrand empStoreHouse : list1){
                if(empStoreHouse.getEmpId().equals(SharedPreference.getPreferString("id"))){
                    brandList = empStoreHouse.getBrandList();
                }
            }

            if(!StringUtil.isEmpty(brandList)){
                String [] list2 =  brandList.split("_");
                if(list2.length > 0){
                    for(String s : list2){
                        for(ShopNew wareHouse : list){
                            if(s.equals(wareHouse.getBrandId())){
                                tmpList.add(wareHouse);
                            }
                        }
                    }
                }
            } else {
                tmpList.addAll(list);
            }
            Log.d(TAG, "tbl_productbrand:" + list.size());

            List<ShopNew> tmpList1 = new ArrayList<>();
            try {
                ShopTypeBean shopTypeBean = new Test().getProductByBrand();
                List<ShopTypeBean.ShopType> list4 = shopTypeBean.getBrandList();
                if(list4 != null && list4.size() > 0){
                    for(ShopTypeBean.ShopType shopType : list4){
                        for(ShopNew shopNew : tmpList){
                            if (shopType.getBrandId().equals(shopNew.getBrandId())){
                                if(shopType.getTypeGroupList() != null && shopType.getTypeGroupList().size() > 0) {
                                    shopNew.setBrandProducts(JSONArray.toJSONString(shopType.getTypeGroupList()));
                                    Log.d(TAG, "ressetBrandProducts:" + shopType.getBrandId() + " " + shopType.getBrandName() + " " + shopType.getTypeGroupList().size());
                                    tmpList1.add(shopNew);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            BrandDB brandDB = new BrandDB();
            brandDB.addAllBrand(tmpList1);
        }
    }

    private boolean hasEmpBrand(String s) {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from EmpBrand where employer_id =? ", new String[]{s});
        if (cursor.getCount() > 0) {
            cursor.close();
            Log.d(TAG, "hasEmpBrand true");
            return true;
        } else {
            Log.d(TAG, "hasEmpBrand false");
            cursor.close();
            return false;
        }
    }

    public List<EmpBrand> findAllCustomer() {
        List<EmpBrand> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from EmpBrand", new String[]{});
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            EmpBrand customer = new EmpBrand();
            customer.setDealerId(cursor.getString(1));
            customer.setEmpId(cursor.getString(2));
            customer.setBrandList(cursor.getString(3));
            Log.d(TAG, "findAllCustomer:" + cursor.getString(3) + " " + cursor.getString(2) + " " + cursor.getString(1));
            list.add(customer);
        }
        cursor.close();
        //db.close();
        Log.d(TAG, "findAllCustomer:" + list.size());
        return list;
    }

    public long getMaxModifyTime() {
        long param = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select max(modifyTime)from EmpBrand ", new String[]{});
        Log.d(TAG, "getMaxModifyTime:getCount" + cursor.getCount());
        if (cursor.moveToFirst()) {

            param = cursor.getLong(0);
        }
        cursor.close();
        Log.d(TAG, "getMaxModifyTime:param" + param);
        return param;
    }

    public void deleteAll() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM EmpBrand");
        Log.d(TAG, "deleteAllCustomer ");
    }

    public boolean hasData() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from EmpBrand", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "EmpBrand true");
            return true;
        } else {
            Log.d(TAG, "EmpBrand false");
            cursor.close();
            return false;
        }
    }

}
